<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-06-24 16:34:00
 * @Description: 监测数据管理模块 - 支持测站类型字段
-->
<template>
  <div
    class="monitoring-data-management"
    :style="{ height: view.height - 120 + 'px' }"
  >
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline label-width="120px">
        <el-form-item label="测站编码">
          <el-input
            v-model="searchForm.stationCode"
            placeholder="请输入测站编码"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="数据类型">
          <el-input
            v-model="searchForm.dataType"
            placeholder="请输入数据类型"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <!-- 新增：测站类型编码查询 -->
        <el-form-item label="测站类型编码">
          <el-select
            v-model="searchForm.stationTypeCode"
            placeholder="请选择测站类型"
            style="width: 200px"
            clearable
            filterable
          >
            <el-option
              v-for="item in stationTypeOptions"
              :key="item.stationTypeCode"
              :label="`${item.stationTypeCode} - ${item.stationTypeName}`"
              :value="item.stationTypeCode"
            />
          </el-select>
        </el-form-item>
        <!-- 新增：测站类型名称查询 -->
        <el-form-item label="测站类型名称">
          <el-input
            v-model="searchForm.stationTypeName"
            placeholder="请输入测站类型名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchForm.endDate"
            type="datetime"
            placeholder="选择结束日期"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="数值范围">
          <el-input-number
            v-model="searchForm.minValue"
            placeholder="最小值"
            style="width: 120px"
          />
          <span style="margin: 0 8px">-</span>
          <el-input-number
            v-model="searchForm.maxValue"
            placeholder="最大值"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card" shadow="never">
      <el-row :gutter="16">
        <el-col :span="18">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增数据
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="success" @click="handleBatchImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="warning" @click="handleCleanup">
            <el-icon><DeleteFilled /></el-icon>
            清理过期数据
          </el-button>
          <el-button @click="handleStatistics">
            <el-icon><DataAnalysis /></el-icon>
            数据统计
          </el-button>
          <!-- 新增：缓存管理按钮 -->
          <el-button type="info" @click="handleRefreshCache">
            <el-icon><Refresh /></el-icon>
            刷新缓存
          </el-button>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
        style="width: 100%"
        :height="view.height - 480"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="stationCode" label="测站编码" width="120" />
        <el-table-column prop="stationName" label="测站名称" width="150" />
        <!-- 新增：测站类型相关列 -->
        <el-table-column
          prop="stationTypeCode"
          label="测站类型编码"
          width="120"
        />
        <el-table-column
          prop="stationTypeName"
          label="测站类型名称"
          width="150"
        />
        <el-table-column prop="dataType" label="数据类型编码" width="120" />
        <el-table-column prop="dataTypeName" label="数据类型名称" width="150" />
        <el-table-column prop="monitoringDate" label="监测时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.monitoringDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="monitoringValue" label="监测值" width="120">
          <template #default="scope">
            {{ formatValue(scope.row.monitoringValue) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="测站编码" prop="stationCode">
              <el-select
                v-model="formData.stationCode"
                placeholder="请选择测站编码"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in stationInfoOptions"
                  :key="item.stcd"
                  :label="`${item.stcd} - ${item.stnm || '未命名'}`"
                  :value="item.stcd"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据类型" prop="dataType">
              <el-input
                v-model="formData.dataType"
                placeholder="请输入数据类型"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <!-- 新增：测站类型选择 -->
          <el-col :span="12">
            <el-form-item label="测站类型编码" prop="stationTypeCode">
              <el-select
                v-model="formData.stationTypeCode"
                placeholder="请选择测站类型"
                filterable
                style="width: 100%"
                @change="handleStationTypeChange"
              >
                <el-option
                  v-for="item in stationTypeOptions"
                  :key="item.stationTypeCode"
                  :label="`${item.stationTypeCode} - ${item.stationTypeName}`"
                  :value="item.stationTypeCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测站类型名称">
              <el-input
                v-model="formData.stationTypeName"
                placeholder="自动填入"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="监测时间" prop="monitoringDate">
              <el-date-picker
                v-model="formData.monitoringDate"
                type="datetime"
                placeholder="选择监测时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测值" prop="monitoringValue">
              <el-input-number
                v-model="formData.monitoringValue"
                :precision="4"
                placeholder="请输入监测值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="监测数据详情" width="700px">
      <el-descriptions :column="2" :border="true">
        <el-descriptions-item label="测站编码">
          {{ detailData.stationCode }}
        </el-descriptions-item>
        <el-descriptions-item label="测站名称">
          {{ detailData.stationName || "-" }}
        </el-descriptions-item>
        <!-- 新增：测站类型信息 -->
        <el-descriptions-item label="测站类型编码">
          {{ detailData.stationTypeCode || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="测站类型名称">
          {{ detailData.stationTypeName || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="数据类型编码">
          {{ detailData.dataType || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="数据类型名称">
          {{ detailData.dataTypeName || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="监测时间">
          {{ formatDate(detailData.monitoringDate) }}
        </el-descriptions-item>
        <el-descriptions-item label="监测值">
          {{ formatValue(detailData.monitoringValue) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(detailData.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(detailData.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog v-model="importVisible" title="批量导入监测数据" width="500px">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls,.csv"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <template #tip>
          <div class="el-upload__tip">
            支持 .xlsx、.xls、.csv 格式文件，大小不超过10MB<br />
            文件应包含以下列：测站编码、数据类型、测站类型编码、监测时间、监测值
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleImportConfirm"
            :loading="importLoading"
            :disabled="fileList.length === 0"
          >
            确定导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 清理过期数据对话框 -->
    <el-dialog v-model="cleanupVisible" title="清理过期数据" width="400px">
      <el-form label-width="120px">
        <el-form-item label="清理日期前的数据">
          <el-date-picker
            v-model="cleanupDate"
            type="date"
            placeholder="选择清理日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cleanupVisible = false">取消</el-button>
          <el-button
            type="danger"
            @click="handleCleanupConfirm"
            :loading="cleanupLoading"
          >
            确定清理
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据统计对话框 -->
    <el-dialog v-model="statisticsVisible" title="数据统计" width="1000px">
      <el-tabs v-model="activeStatisticsTab" type="card">
        <!-- 测站统计标签页 -->
        <el-tab-pane label="测站统计" name="station">
          <el-form :model="statisticsForm" inline label-width="120px">
            <el-form-item label="测站编码">
              <el-input
                v-model="statisticsForm.stationCode"
                placeholder="请输入测站编码"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="测站类型">
              <el-select
                v-model="statisticsForm.stationTypeCode"
                placeholder="请选择测站类型"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in stationTypeOptions"
                  :key="item.stationTypeCode"
                  :label="`${item.stationTypeCode} - ${item.stationTypeName}`"
                  :value="item.stationTypeCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleGetStatistics">
                查询统计
              </el-button>
            </el-form-item>
          </el-form>

          <div v-if="statisticsData" class="statistics-content">
            <el-descriptions :column="3" :border="true">
              <el-descriptions-item label="测站编码">
                {{ statisticsData.stationCode }}
              </el-descriptions-item>
              <el-descriptions-item label="测站名称">
                {{ statisticsData.stationName || "-" }}
              </el-descriptions-item>
              <el-descriptions-item label="测站类型">
                {{ statisticsData.stationTypeName || "-" }}
              </el-descriptions-item>
              <el-descriptions-item label="数据总数">
                {{ statisticsData.totalCount }}
              </el-descriptions-item>
              <el-descriptions-item label="平均值">
                {{ formatValue(statisticsData.avgValue) }}
              </el-descriptions-item>
              <el-descriptions-item label="最大值">
                {{ formatValue(statisticsData.maxValue) }}
              </el-descriptions-item>
              <el-descriptions-item label="最小值">
                {{ formatValue(statisticsData.minValue) }}
              </el-descriptions-item>
              <el-descriptions-item label="最新数据时间">
                {{ formatDate(statisticsData.latestDate) }}
              </el-descriptions-item>
              <el-descriptions-item label="最早数据时间">
                {{ formatDate(statisticsData.earliestDate) }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-tab-pane>

        <!-- 按测站统计标签页 -->
        <el-tab-pane label="按测站统计" name="byStation">
          <div class="station-count-section">
            <el-button
              type="primary"
              @click="handleCountByStation"
              style="margin-bottom: 16px"
            >
              刷新统计
            </el-button>
            <el-table :data="stationCountData" border stripe max-height="400">
              <el-table-column prop="stationCode" label="测站编码" />
              <el-table-column prop="stationTypeCode" label="测站类型编码" />
              <el-table-column prop="count" label="数据数量" />
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 新增：按测站类型统计标签页 -->
        <el-tab-pane label="按测站类型统计" name="byStationType">
          <div class="station-type-count-section">
            <el-button
              type="primary"
              @click="handleCountByStationType"
              style="margin-bottom: 16px"
            >
              刷新统计
            </el-button>
            <el-table
              :data="stationTypeCountData"
              border
              stripe
              max-height="400"
            >
              <el-table-column prop="stationTypeCode" label="测站类型编码" />
              <el-table-column prop="stationTypeName" label="测站类型名称" />
              <el-table-column prop="count" label="数据数量" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statisticsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Upload,
  Download,
  UploadFilled,
  DeleteFilled,
  DataAnalysis,
} from "@element-plus/icons-vue";
import axios from "axios";
import api from "@/api/api";

// 响应式数据
const loading = ref(false);
const saveLoading = ref(false);
const importLoading = ref(false);
const cleanupLoading = ref(false);
const dialogVisible = ref(false);
const detailVisible = ref(false);
const importVisible = ref(false);
const cleanupVisible = ref(false);
const statisticsVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref("");

// 统计标签页
const activeStatisticsTab = ref("station");

// 表格数据
const tableData = ref([]);
const selectedRows = ref([]);

// 选项数据
const stationTypeOptions = ref([]);
const stationInfoOptions = ref([]);

// 搜索表单
const searchForm = reactive({
  stationCode: "",
  dataType: "",
  stationTypeCode: "", // 新增
  stationTypeName: "", // 新增
  startDate: null,
  endDate: null,
  minValue: null,
  maxValue: null,
});

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

// 表单数据和规则
const formRef = ref();
const formData = reactive({
  id: "",
  stationCode: "",
  dataType: "",
  stationTypeCode: "", // 新增
  stationTypeName: "", // 新增
  monitoringDate: null,
  monitoringValue: null,
});

const formRules = reactive({
  stationCode: [
    { required: true, message: "请选择测站编码", trigger: "change" },
  ],
  dataType: [{ required: true, message: "请输入数据类型", trigger: "blur" }],
  monitoringDate: [
    { required: true, message: "请选择监测时间", trigger: "change" },
  ],
  monitoringValue: [
    { required: true, message: "请输入监测值", trigger: "blur" },
  ],
});

// 详情数据
const detailData: any = reactive({});

// 文件上传
const uploadRef = ref();
const fileList = ref([]);

// 清理数据
const cleanupDate = ref(null);

// 统计数据
const statisticsForm = reactive({
  stationCode: "",
  stationTypeCode: "", // 新增
});
const statisticsData = ref(null);
const stationCountData = ref([]);
const stationTypeCountData = ref([]); // 新增

// 生命周期
onMounted(() => {
  loadData();
  loadStationTypes();
  loadStationInfo();
});

// 窗口大小变化监听
window.onresize = () => {
  view.height = window.innerHeight;
};

// 修改后的加载测站类型选项方法 - 参照第二个组件的方式
const loadStationTypes = async () => {
  try {
    const response = await axios.get("/algorithmApi/api1/station-type1/list");
    if (response.data.code === 200) {
      stationTypeOptions.value = response.data.data || [];
    } else {
      ElMessage.error(response.data.message || "获取测站类型选项失败");
    }
  } catch (error) {
    console.error("加载测站类型选项失败:", error);
    ElMessage.error("加载测站类型选项失败");
  }
};

// 加载测站信息选项
const loadStationInfo = async () => {
  api.stationInfoManage.getAllStationInfo(
    {},
    (response: any) => {
      const responseData = response.data || response;
      if (responseData.code === 200) {
        stationInfoOptions.value = responseData.data || [];
      }
    },
    (error: any) => {
      console.error("加载测站信息失败:", error);
    }
  );
};

// 测站类型选择变化处理
const handleStationTypeChange = (stationTypeCode: string) => {
  const selectedType = stationTypeOptions.value.find(
    (item: any) => item.stationTypeCode === stationTypeCode
  );
  if (selectedType) {
    formData.stationTypeName = selectedType.stationTypeName;
  } else {
    formData.stationTypeName = "";
  }
};

// 方法定义
const loadData = async () => {
  loading.value = true;
  try {
    // 清理空参数
    const cleanParams = {};
    Object.keys(searchForm).forEach((key) => {
      const value = searchForm[key];
      if (key === "startDate" || key === "endDate") {
        if (value !== null && value !== undefined) {
          cleanParams[key] =
            value instanceof Date
              ? value.toISOString()
              : new Date(value).toISOString();
        }
      } else {
        if (value !== "" && value !== null && value !== undefined) {
          cleanParams[key] = value;
        }
      }
    });

    const params = {
      ...cleanParams,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    };

    console.log("请求参数:", params);

    api.monitoringDataManage.getMonitoringDataPage(
      params,
      (response: any) => {
        console.log("响应数据:", response);
        if (response && response.data && response.data.code === 200) {
          const responseData = response.data.data;
          tableData.value.length = 0;
          tableData.value = responseData.list || [];
          pagination.total = responseData.total || 0;
          pagination.pageNum = responseData.pageNum || pagination.pageNum;
          pagination.pageSize = responseData.pageSize || pagination.pageSize;
        } else {
          ElMessage.error(
            response?.data?.message || response?.message || "查询失败"
          );
        }
        loading.value = false;
      },
      (error: any) => {
        console.error("请求错误:", error);
        ElMessage.error("查询失败: " + (error.message || error));
        loading.value = false;
      }
    );
  } catch (error) {
    console.error("异常错误:", error);
    ElMessage.error("查询失败");
    loading.value = false;
  }
};

const handleSearch = () => {
  console.log("搜索时的表单数据:", searchForm);
  console.log("开始日期:", searchForm.startDate);
  console.log("结束日期:", searchForm.endDate);
  pagination.pageNum = 1;
  loadData();
};

const handleReset = () => {
  Object.keys(searchForm).forEach((key) => {
    if (key === "startDate" || key === "endDate") {
      searchForm[key] = null;
    } else if (key === "minValue" || key === "maxValue") {
      searchForm[key] = null;
    } else {
      searchForm[key] = "";
    }
  });
  pagination.pageNum = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

// 新增：刷新缓存
const handleRefreshCache = () => {
  ElMessageBox.confirm(
    "确定要刷新缓存吗？这将重新加载所有相关数据。",
    "确认刷新缓存",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  ).then(() => {
    api.monitoringDataManage.refreshCache(
      {},
      (response: any) => {
        const responseData = response.data || response;
        if (responseData.code === 200) {
          ElMessage.success("缓存刷新成功");
          // 重新加载相关数据
          loadData();
          loadStationTypes();
          loadStationInfo();
        } else {
          ElMessage.error(responseData.message || "缓存刷新失败");
        }
      },
      (error: any) => {
        console.error("缓存刷新错误:", error);
        ElMessage.error("缓存刷新失败");
      }
    );
  });
};

const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增监测数据";
  resetForm();
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  isEdit.value = true;
  dialogTitle.value = "编辑监测数据";
  Object.assign(formData, {
    ...row,
    monitoringDate: row.monitoringDate ? new Date(row.monitoringDate) : null,
  });
  dialogVisible.value = true;
};

const handleView = (row: any) => {
  Object.assign(detailData, row);
  detailVisible.value = true;
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除这条监测数据吗？`, "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api.monitoringDataManage.deleteMonitoringData(
      { id: row.id },
      (response: any) => {
        const responseData = response.data || response;
        if (responseData.code === 200) {
          ElMessage.success("删除成功");
          loadData();
        } else {
          ElMessage.error(responseData.message || "删除失败");
        }
      },
      (error: any) => {
        console.error("删除错误:", error);
        ElMessage.error("删除失败");
      }
    );
  });
};

const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
    "确认批量删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    const ids = selectedRows.value.map((row: any) => row.id);
    api.monitoringDataManage.batchDeleteMonitoringData(
      { ids },
      (response: any) => {
        const responseData = response.data || response;
        if (responseData.code === 200) {
          ElMessage.success(`成功删除 ${responseData.data} 条记录`);
          selectedRows.value = [];
          loadData();
        } else {
          ElMessage.error(responseData.message || "批量删除失败");
        }
      },
      (error: any) => {
        console.error("批量删除错误:", error);
        ElMessage.error("批量删除失败");
      }
    );
  });
};

const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saveLoading.value = true;

    const apiMethod = isEdit.value
      ? api.monitoringDataManage.updateMonitoringData
      : api.monitoringDataManage.createMonitoringData;

    apiMethod(
      formData,
      (response: any) => {
        const responseData = response.data || response;
        if (responseData.code === 200) {
          ElMessage.success(isEdit.value ? "更新成功" : "创建成功");
          dialogVisible.value = false;
          loadData();
        } else {
          ElMessage.error(responseData.message || "保存失败");
        }
        saveLoading.value = false;
      },
      (error: any) => {
        console.error("保存错误:", error);
        ElMessage.error("保存失败");
        saveLoading.value = false;
      }
    );
  } catch (error) {
    console.log("表单验证失败", error);
    saveLoading.value = false;
  }
};

const handleBatchImport = () => {
  fileList.value = [];
  importVisible.value = true;
};

const handleFileChange = (file: any) => {
  fileList.value = [file];
};

const handleImportConfirm = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning("请选择要导入的文件");
    return;
  }

  importLoading.value = true;
  // 实际项目中需要解析文件并调用API
  setTimeout(() => {
    ElMessage.success("导入成功");
    importVisible.value = false;
    importLoading.value = false;
    loadData();
  }, 2000);
};

const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

const handleCleanup = () => {
  cleanupDate.value = null;
  cleanupVisible.value = true;
};

const handleCleanupConfirm = () => {
  if (!cleanupDate.value) {
    ElMessage.warning("请选择清理日期");
    return;
  }

  ElMessageBox.confirm(
    `确定要清理 ${cleanupDate.value} 之前的所有数据吗？此操作不可逆！`,
    "确认清理",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    cleanupLoading.value = true;
    const beforeDate = new Date(cleanupDate.value).toISOString();

    api.monitoringDataManage.deleteExpiredData(
      { beforeDate },
      (response: any) => {
        const responseData = response.data || response;
        if (responseData.code === 200) {
          ElMessage.success(`成功清理 ${responseData.data} 条过期数据`);
          cleanupVisible.value = false;
          loadData();
        } else {
          ElMessage.error(responseData.message || "清理失败");
        }
        cleanupLoading.value = false;
      },
      (error: any) => {
        console.error("清理错误:", error);
        ElMessage.error("清理失败");
        cleanupLoading.value = false;
      }
    );
  });
};

const handleStatistics = () => {
  statisticsForm.stationCode = "";
  statisticsForm.stationTypeCode = "";
  statisticsData.value = null;
  stationCountData.value = [];
  stationTypeCountData.value = [];
  statisticsVisible.value = true;
  activeStatisticsTab.value = "station";

  // 默认加载所有测站统计
  handleCountByStation();
};

const handleGetStatistics = () => {
  if (!statisticsForm.stationCode) {
    ElMessage.warning("请输入测站编码");
    return;
  }

  const params = {
    stationCode: statisticsForm.stationCode,
    stationTypeCode: statisticsForm.stationTypeCode,
  };

  api.monitoringDataManage.getDataStatistics(
    params,
    (response: any) => {
      const responseData = response.data || response;
      if (responseData.code === 200) {
        statisticsData.value = responseData.data;
      } else {
        ElMessage.error(responseData.message || "获取统计失败");
      }
    },
    (error: any) => {
      console.error("统计错误:", error);
      ElMessage.error("获取统计失败");
    }
  );
};

const handleCountByStation = () => {
  api.monitoringDataManage.countByStation(
    {},
    (response: any) => {
      const responseData = response.data || response;
      if (responseData.code === 200) {
        stationCountData.value = responseData.data || [];
      } else {
        console.error("获取测站统计失败:", responseData.message);
      }
    },
    (error: any) => {
      console.error("测站统计错误:", error);
    }
  );
};

// 新增：按测站类型统计
const handleCountByStationType = () => {
  api.monitoringDataManage.countByStationType(
    {},
    (response: any) => {
      const responseData = response.data || response;
      if (responseData.code === 200) {
        stationTypeCountData.value = responseData.data || [];
      } else {
        console.error("获取测站类型统计失败:", responseData.message);
      }
    },
    (error: any) => {
      console.error("测站类型统计错误:", error);
    }
  );
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  loadData();
};

const handleCurrentChange = (page: number) => {
  pagination.pageNum = page;
  loadData();
};

const resetForm = () => {
  Object.keys(formData).forEach((key) => {
    if (key === "monitoringDate") {
      formData[key] = null;
    } else if (key === "monitoringValue") {
      formData[key] = null;
    } else {
      formData[key] = "";
    }
  });
};

const formatDate = (date: string) => {
  if (!date) return "-";
  return new Date(date).toLocaleString("zh-CN");
};

const formatValue = (value: any) => {
  if (value === null || value === undefined || value === "") {
    return "-";
  }
  const num = Number(value);
  if (isNaN(num)) {
    return "-";
  }
  return num.toFixed(4);
};

// 视图高度
const view = reactive({
  height: window.innerHeight,
});

window.onresize = function () {
  view.height = window.innerHeight;
};
</script>

<style lang="scss" scoped>
.monitoring-data-management {
  padding: 16px;

  .search-card,
  .operation-card,
  .table-card {
    margin-bottom: 16px;
  }

  .text-right {
    text-align: right;
  }

  .pagination-wrapper {
    margin-top: 16px;
    text-align: right;
  }

  .dialog-footer {
    text-align: right;
  }

  .statistics-content {
    margin: 20px 0;
  }

  .station-count-section,
  .station-type-count-section {
    margin-top: 20px;

    h4 {
      margin-bottom: 10px;
      color: #303133;
    }
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }
}
</style>
